﻿using Microsoft.AspNetCore.Mvc;

namespace RuoVea.Swms.Server.Service
{
    /// <summary>
    /// 产品类别管理
    /// </summary>
    [ApiExplorerSettings(GroupName = "swms")]
    public class CategoryService : IApplicationService
    {
        private readonly SugarRepository<WmsCategory> _thisRepository;
        private readonly SugarRepository<WmsProduct> _productRepo;
        
        private readonly ICurrentUser _currentUser;

        public CategoryService( 
            SugarRepository<WmsCategory> categoryRepo,
            SugarRepository<WmsProduct> productRepo,
            ICurrentUser currentUser)
        { 
            _thisRepository = categoryRepo;
            _productRepo=productRepo;
            _currentUser = currentUser;
        }

        /// <summary>
        /// 查询所有/分页
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns> 
        public async Task<RestfulResult<PageResult<WmsCategory>>> GetPagesAsync(PageParam? data)
        {
            var restful = new RestfulResult<PageResult<WmsCategory>>() { Code = CodeStatus.OK };
            data ??= new PageParam { PageNo = 1, PageSize = 10 };
            var query = await _thisRepository.AsQueryable()
                .Where(u => u.Creator == _currentUser.UserId)
                .ToPageAsync(data.PageNo, data.PageSize);

            restful.Data = query;
            return restful;
        }
        /// <summary>
        /// 获取所有位置列表（用于下拉选择）
        /// </summary>
        public async Task<RestfulResult<List<WmsCategory>>> GetlistAsync()
        {
            var restful = new RestfulResult<List<WmsCategory>> { Code = CodeStatus.OK };
            var locations = await _thisRepository.GetListAsync();
            restful.Data = locations;
            return restful;
        }
        /// <summary>
        /// 添加产品类别
        /// </summary>
        [UnitOfWork]
        public async Task<RestfulResult> AddAsync(WmsCategory data)
        {
            var restful = new RestfulResult { Code = CodeStatus.BadRequest };

            // 验证编码唯一性
            var exists = await _thisRepository.IsAnyAsync(u => u.Code == data.Code);
            if (exists)
            {
                restful.Message = "类别编码已存在";
                return restful;
            }

            // 验证父类别是否存在
            if (data.ParentId.HasValue && data.ParentId.Value > 0)
            {
                var parentExists = await _thisRepository.IsAnyAsync(u => u.Id == data.ParentId.Value);
                if (!parentExists)
                {
                    restful.Message = "父类别不存在";
                    return restful;
                }
            }

            data.Creator = _currentUser.UserId;
            bool result = await _thisRepository.InsertAsync(data);

            restful.Code = result ? CodeStatus.OK : CodeStatus.BadRequest;
            restful.Data = result;
            restful.Message = result ? "添加成功" : "添加失败";
            return restful;
        }

        /// <summary>
        /// 更新产品类别
        /// </summary>
        public async Task<RestfulResult> UpdateAsync(WmsCategory data)
        {
            var restful = new RestfulResult { Code = CodeStatus.BadRequest };

            // 验证类别是否存在
            var exists = await _thisRepository.IsAnyAsync(u => u.Id == data.Id);
            if (!exists)
            {
                restful.Message = "类别不存在";
                return restful;
            }

            // 防止循环引用
            if (data.ParentId.HasValue && data.ParentId.Value == data.Id)
            {
                restful.Message = "不能将类别设置为自己的父类别";
                return restful;
            }

            bool result = await _thisRepository.UpdateAsync(data);

            restful.Code = result ? CodeStatus.OK : CodeStatus.BadRequest;
            restful.Message = result ? "更新成功" : "更新失败";
            restful.Data = result;
            return restful;
        }

        /// <summary>
        /// 删除产品类别
        /// </summary>
        public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
        {
            var restful = new RestfulResult { Code = CodeStatus.BadRequest };

            // 检查是否有子类别
            var hasChildren = await _thisRepository.IsAnyAsync(u => u.ParentId == data.Id);
            if (hasChildren)
            {
                restful.Message = "请先删除所有子类别";
                return restful;
            }

            // 检查是否有产品使用此类别
            var hasProducts = await _productRepo.IsAnyAsync(u => u.CategoryId == data.Id);
            if (hasProducts)
            {
                restful.Message = "有产品使用此类别，无法删除";
                return restful;
            }

            bool result = await _thisRepository.DeleteByIdAsync(data.Id);
            restful.Data = result;
            restful.Code = result ? CodeStatus.OK : CodeStatus.BadRequest;
            restful.Message = result ? "删除成功" : "删除失败";
            return restful;
        }
    }
}